package com.mlnx.bluwifi.controller;


import com.alibaba.fastjson.JSONObject;
import com.mlnx.bluwifi.manager.SpoPolicy;
import com.mlnx.bluwifi.pojo.DataCache;
import com.mlnx.bluwifi.pojo.dto.Connect;
import com.mlnx.bluwifi.pojo.dto.ConnectBlu;
import com.mlnx.bluwifi.utils.HttpUtil;
import com.mlnx.bluwifi.utils.SpolanyaUtils;
import com.mlnx.common.entity.Response;
import com.mlnx.common.entity.ResponseData;
import com.mlnx.data.entity.SpoInfo;
import com.mlnx.device.service.LanyaDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.shan.spring.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Api(value = "蓝牙AP接口", tags = "蓝牙AP接口")
@RestController
@RequestMapping("mlnx_device/blue")
public class BlueSpoController extends BaseController {
    @Autowired
    private LanyaDeviceService lanyaDeviceService;

    @RequestMapping(value = "/get/spo", method = {RequestMethod.GET})
    public Response getSpoDeviceInfo(@RequestParam String blueMac, @RequestParam String ip) {
        ResponseData response = new ResponseData();
        String str = HttpUtil.sendGet(SpolanyaUtils.getConnectDevice(ip), "connection_state" +
                "=connected&mac=" + blueMac + "&access_token=");
        List<SpoInfo> list = new ArrayList<>();
        Connect connect = JSONObject.parseObject(str, Connect.class);
        if (connect == null) {
            response.setCode("3000");
            response.setMsg("Ap无法连接，解析数据为空:" + blueMac);
        } else {
            if (connect.getNodes().get(0).getId() != null && connect.getNodes().size() > 0) {
                for (ConnectBlu connectBlu : connect.getNodes()) {
                    DataCache dataCache = SpoPolicy.getInstance().getDataCache(connectBlu.getId());
                    if (dataCache.getSpoInfo() != null) {
                        list.add(dataCache.getSpoInfo());
                    }
                }
            }
            response.setObj(list);
        }
        return response;

    }

    @ApiOperation("获取AP数据")
    @RequestMapping(value = "/get/ap", method = {RequestMethod.GET})
    public Response getApDeviceInfo() {
        ResponseData response = new ResponseData();
        response.setObj(lanyaDeviceService.list());

        return response;

    }

    @ApiOperation("新增AP")
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    public Response addAp(com.mlnx.device.entity.LanyaDevice lanyaDevice) {
        lanyaDeviceService.save(lanyaDevice);
        return result();

    }
}
